//
//  JobDetailVC.m
//  MyProject
//
//  Created by jiaming yan on 2018/3/5.
//  Copyright © 2018年 yanjiaming. All rights reserved.
//

#import "JobDetailVC.h"
#import "HXTagsView.h"
#import "HXTagAttribute.h"
#import "AnswersTableViewCell.h"
#import "InterviewExperienceTableViewCell.h"
#import "CompanyVC.h"
#import "CompanyMainViewController.h"
#import "StringAndIndexModel.h"
#import "ReportOrCancelViewController.h"
#import "PositionReviewModel.h"
#import "keepInJobViewController.h"
#import "SendResumeVC.h"

@interface JobDetailVC ()<UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) IBOutlet UIView *headView;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic)  NSMutableArray *arrData;
@property (weak, nonatomic) IBOutlet HXTagsView *tagBackView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightOfTags;

/**职位详情*/
@property (weak, nonatomic) IBOutlet HXTagsView *jobTagBackView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightOfJobTags;
@property (weak, nonatomic) IBOutlet UILabel *jobDesLabel;
@property (weak, nonatomic) IBOutlet UIButton *jobDesMoreButton;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *jobDesMoreButtonHeight;

@property (weak, nonatomic) IBOutlet UILabel *locationLabel;

@property (nonatomic, strong) NSMutableArray *reviewArray;

@end

@implementation JobDetailVC {
    NSInteger _positonListPageNo;
    BOOL _displayMoreHelpBtn;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.navigationController.navigationBarHidden = YES;
    
    NSString *version = [UIDevice currentDevice].systemVersion;
    if (version.doubleValue >= 11.0) {
        self.navViewTopHeight.constant = 0;
        self.headerBackInfoViewTopHeight.constant = 50;
    } else {
        self.navViewTopHeight.constant = 20;
//        self.headerBackViewHeight.constant = 205;
        self.headerBackInfoViewTopHeight.constant = 70;
    }
    
    [self setupSubViews];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _positonListPageNo = 1;
        [self loadPositionInfoData];
        [self loadPositionReviewList];
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        _positonListPageNo += 1;
        [self loadPositionReviewList];
    }];
    // 获取用户的收藏信息
    [self getUserCollected];
    [self.tableView.mj_header beginRefreshing];
}

- (void)setupSubViews{
    self.jobDesMoreButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 10);
    HXTagAttribute *model = [[HXTagAttribute alloc]init];
    model.borderWidth  = 0;
    model.borderColor  = kClearColor;
    model.cornerRadius  = 8;
    model.titleSize  = 11;
    model.textColor  = UIColorFromRGB(0x00BCCC);
    model.normalBackgroundColor  = UIColorFromRGB(0xE7F4F6);
    model.selectedBackgroundColor  = UIColorFromRGB(0xE7F4F6);
    model.selectedTextColor = UIColorFromRGB(0x00BCCC);
//    model.textColor  = [UIColor redColor];
//    model.normalBackgroundColor  = [UIColor yellowColor];
//    model.selectedBackgroundColor  = [UIColor yellowColor];
    model.tagSpace  = 15;
    _tagBackView.tagAttribute = model;
//    [_tagBackView reloadData];
//    _jobTagBackView.layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _jobTagBackView.tagAttribute = model;

    
    [self loadHeaderHeight];
    self.tableView.tableHeaderView = self.headView;
    [self.tableView registerNib:[UINib nibWithNibName:@"InterviewExperienceTableViewCell" bundle:nil] forCellReuseIdentifier:@"InterviewExperienceTableViewCell"];
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.estimatedRowHeight = 184.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
}

/** 加载数据 */
- (void)loadPositionInfoData {
    WS(weakSelf)
    [SendRequest getPostionInfoByPositionId:self.positionId result:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
        if([result[@"result"] integerValue] == 1) {
            SaintiLog(@"根据职位ID查询职位信息 = %@", [result objectForKey:@"data"]);
            weakSelf.positionModel = [PositionModel mj_objectWithKeyValues:[result objectForKey:@"data"]];
            
//            weakSelf.positionModel.positionRemark = @"岗位职责1.参与公司的战略分析，制定、推进和实施产品规划方案；跟进业务场景和业务发展，对业务数据进行手机、处理、分析、挖掘、使用。2.把我国内外移动互联网市场趋势，定期对自身产品及行业，竞争对手等进行数据分析，制定产品竞争...";
//            weakSelf.positionModel.workingPlace = @"高新园区-高新街道三丰大厦-创业e港C座401号两行的情况";
            
            [weakSelf resetMainView];
        } else {
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
    }];
}

/** 显示数据 */
- (void)resetMainView {
    self.headerPositionNameL.text = self.positionModel.positionName;
    self.headerPositionSalaryL.text = [NSString stringWithFormat:@"%@k-%@k", self.positionModel.minSalary, self.positionModel.maxSalary];
    self.headerPositionRegionL.text = [NSString stringWithFormat:@"%@-%@", self.positionModel.regionName, self.positionModel.workingPlaceTradingArea];
    self.headerPositionExperienceL.text = self.positionModel.requiredExperienceName;
    self.headerPositionEducateL.text = self.positionModel.requiredEducationalName;
    self.headerPositionSourceL.text = [NSString stringWithFormat:@"数据来源：%@", self.positionModel.sourceName];
    
    _tagBackView.tags = [self.positionModel.welfareTags componentsSeparatedByString:@","];
    [_tagBackView reloadData];
    CGFloat height = [HXTagsView getHeightWithTags:self.tagBackView.tags layout:self.tagBackView.layout tagAttribute:self.tagBackView.tagAttribute width:kScreenWidth-30];
    self.heightOfTags.constant = height;
    
    [self.headerCompanyLogoIV sd_setImageWithURL:ImageURLWithKey(self.positionModel.companyLogo) placeholderImage:PlaceholderImageCompany];
    self.headerCompanyNameL.text = self.positionModel.companyAbbreviatedName;
    self.headerCompanyInfoL.text = [NSString stringWithFormat:@"%@/%@/%@", self.positionModel.companyIndustry, self.positionModel.financingScale, self.positionModel.personnelScale];
    
    self.headerCompanyNumPeopleL.text = [NSString stringWithFormat:@"已有%@名认证员工", self.positionModel.recruitCount];
    
    _jobTagBackView.tags = [self.positionModel.skillsTags componentsSeparatedByString:@","];
    [_jobTagBackView reloadData];
    CGFloat jobTagHeight = [HXTagsView getHeightWithTags:_jobTagBackView.tags layout:_jobTagBackView.layout tagAttribute:_jobTagBackView.tagAttribute width:kScreenWidth-30];
    self.heightOfJobTags.constant = jobTagHeight;
    
    if (self.positionModel.positionRemark && self.positionModel.positionRemark.length > 0) {
        self.headerJobDescL.text = self.positionModel.positionRemark;
        
        CGFloat descH = [Tool sizeWithText:self.positionModel.positionRemark font:[UIFont fontWithName:@"PingFang SC" size:14] maxW:kScreenWidth - 64].height;
        NSInteger lineCount = descH / self.headerJobDescL.font.lineHeight;
        
        if (lineCount < 3) {
            self.jobDesMoreButton.hidden = YES;
            self.jobDetailViewLine.hidden = YES;
            
            self.headerJobDescL.numberOfLines = lineCount == 0 ? 1 : lineCount;
            _displayMoreHelpBtn = NO;
            self.jobDesMoreButtonHeight.constant = 0;
        } else {
            self.jobDesMoreButton.hidden = NO;
            self.jobDetailViewLine.hidden = NO;
            
            self.headerJobDescL.numberOfLines = 3;
            _displayMoreHelpBtn = YES;
            self.jobDesMoreButtonHeight.constant = 40;
        }
        
        self.jobDetailTitleView.hidden = NO;
        self.jobDetailTitleViewHeight.constant = 30;
        self.jobDetailTitleViewIconIV.hidden = NO;
        self.jobDetailTitleViewTitleL.hidden = NO;
    } else {
        self.headerJobDescL.text = @"";
        
        self.jobDesMoreButton.hidden = YES;
        self.jobDetailViewLine.hidden = YES;
        _displayMoreHelpBtn = NO;
        self.jobDesMoreButtonHeight.constant = 0;
        
        self.jobDetailTitleView.hidden = YES;
        self.jobDetailTitleViewHeight.constant = 0;
        self.jobDetailTitleViewIconIV.hidden = YES;
        self.jobDetailTitleViewTitleL.hidden = YES;
    }
    
    self.headerCompanyRegionL.text = self.positionModel.workingPlace;
    self.headerSalaryPositionLeftL.text = [NSString stringWithFormat:@"当前公司·%@", self.positionModel.jobName];
    self.headerSalaryLeftL.text = [NSString stringWithFormat:@"%@k", self.positionModel.positionSalary];
    self.headerSalaryPositionRightL.text = [NSString stringWithFormat:@"%@·%@", self.positionModel.regionName, self.positionModel.jobName];
    self.headerSalaryRightL.text = [NSString stringWithFormat:@"%@k", self.positionModel.positionMinSalary];
    self.headerSalarySourceL.text = @"来自台阶2837个大连同类职位大数据分析";
    
    [self loadHeaderHeight];
}


/** 查询企业职位评价列表 */
- (void)loadPositionReviewList {
    WS(weakSelf)
    [SendRequest getPostionInterviewReviewByPositionId:self.positionId andPageNo:[NSString stringWithFormat:@"%zd", _positonListPageNo] result:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
        if([result[@"result"] integerValue] == 1) {
            SaintiLog(@"查询企业职位评价列表 = %@", [result objectForKey:@"data"]);
            
            NSArray *datas = [PositionReviewModel mj_objectArrayWithKeyValuesArray:[[result objectForKey:@"data"] objectForKey:@"list"]];
            if (_positonListPageNo == 1) {
                [weakSelf.reviewArray removeAllObjects];
                [weakSelf.reviewArray addObjectsFromArray:datas];
                [weakSelf.tableView reloadData];
                [weakSelf.tableView.mj_header endRefreshing];
                [weakSelf.tableView.mj_footer endRefreshing];
            } else {
                [weakSelf.reviewArray addObjectsFromArray:datas];
                [weakSelf.tableView reloadData];
                if (datas.count < kNumOfPageIntSize) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                } else {
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
            }
        } else {
            [CommonUtils showToast:[result objectForKey:@"msg"]];
            if (_positonListPageNo == 1) {
                [weakSelf.tableView.mj_header endRefreshing];
            } else {
                [weakSelf.tableView.mj_footer endRefreshing];
            }
        }
    }];
}

#pragma mark ------tableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.reviewArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"InterviewExperienceTableViewCell";
    InterviewExperienceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.selectionStyle =  UITableViewCellSelectionStyleNone;
    cell.model = [self.reviewArray objectAtIndex:indexPath.row];
    return cell;
}

- (void )tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)backButtonClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)moreJobDesButtonClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        self.jobDesLabel.numberOfLines = 0;
    }else{
        self.jobDesLabel.numberOfLines = 3;
    }
    [self loadHeaderHeight];
//    self.tableView.tableHeaderView = self.headView;
}

-(void)loadHeaderHeight{
    [self.locationLabel sizeToFit];
    [self.jobDesLabel sizeToFit];
    
//    CGFloat height = 669+ self.heightOfTags.constant + self.heightOfJobTags.constant + self.jobDesLabel.mj_h + self.locationLabel.mj_h-18.5;
    
    CGFloat jobDetailMoreBtnHeight = _displayMoreHelpBtn ? 40 : 0;
    CGFloat jobDetailHeight = jobDetailMoreBtnHeight + self.headerJobDescL.mj_h;
    
    CGFloat height = 570 + self.heightOfTags.constant + self.jobDetailTitleViewHeight.constant + self.heightOfJobTags.constant + jobDetailHeight + self.locationLabel.mj_h;
    if ([Tool isIphoneX]) {
        self.headView.frame = CGRectMake(0, 0, kScreenWidth, height + 24);
    } else {
        self.headView.frame = CGRectMake(0, 0, kScreenWidth, height);
    }
    self.tableView.tableHeaderView = self.headView;
    [self.tableView reloadData];
}

- (IBAction)companyDetailClick:(id)sender {
    if (!self.positionModel || !self.positionModel.companyId) {
        return;
    }
    CompanyMainViewController *vc = [[CompanyMainViewController alloc] init];
    vc.companyId = self.positionModel.companyId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)sendResumeBtnClick:(id)sender {
    SendResumeVC *vc =[[SendResumeVC alloc]init];

    vc.modalPresentationStyle=UIModalPresentationOverCurrentContext;
    [vc setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
    [self presentViewController:vc animated:YES completion:^{}];
}

- (IBAction)keepInJobBtnClick:(id)sender {
    keepInJobViewController *vc = [[keepInJobViewController alloc] init];
    vc.companyId = self.positionModel.companyId;
    vc.positionId = self.positionModel.positionId;
    [self.navigationController pushViewController:vc animated:YES];
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    self.navigationController.navigationBarHidden = YES;
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    self.navigationController.navigationBarHidden = NO;
}

- (IBAction)tipBtnClick:(id)sender {
    NSArray *msgs = @[@"信息内容不真实", @"泄露/索取个人隐私", @"封建迷信、反动思想、涉黄涉暴等政治敏感内容", @"发布广告/虚假信息/传销等信息", @"辱骂/诽谤/恶意骚扰等人身攻击", @"其他"];
    NSMutableArray *dataArray = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < msgs.count; i++) {
        StringAndIndexModel *model = [[StringAndIndexModel alloc] init];
        if (i == 0) {
            model.index = 1;
        } else {
            model.index = 0;
        }
        model.msg = msgs[i];
        [dataArray addObject:model];
    }
    
    ReportOrCancelViewController *VC = [[ReportOrCancelViewController alloc] init];
    VC.index = 1;
    VC.dataArray = dataArray;
    VC.relatedId = self.positionId;
    VC.relatedType = @"REPORT_TYPE_POSITION";
    [self.navigationController pushViewController:VC animated:YES];
}

- (IBAction)shareBtnClick:(id)sender {
    [self showShareView];
}

- (IBAction)collectBtnClick:(id)sender {
    if (self.collectBtn.selected) {
        // 取消收藏
        WS(weakSelf)
        [self showProgressWithView:self.view animated:YES];
        [SendRequest cancelCollectWithRelatedId:self.positionId result:^(NSDictionary *result, NSError *error) {
            [weakSelf hideProgress:self.view animated:YES];
            result = [CommonUtils decryptDicWithResult:result];
            if([result[@"result"] integerValue] == 1) {
                /**取消收藏成功*/
                self.collectBtn.selected = !self.collectBtn.selected;
            } else {
                [CommonUtils showToast:[result objectForKey:@"msg"]];
            }
        }];
    } else {
        // 收藏
        WS(weakSelf)
        [self showProgressWithView:self.view animated:YES];
        [SendRequest collectWithRelatedId:self.positionId andType:@"COLLECTION_TYPE_POSITION" result:^(NSDictionary *result, NSError *error) {
            [weakSelf hideProgress:self.view animated:YES];
            result = [CommonUtils decryptDicWithResult:result];
            if([result[@"result"] integerValue] == 1) {
                /**收藏成功*/
                self.collectBtn.selected = !self.collectBtn.selected;
            } else {
                [CommonUtils showToast:[result objectForKey:@"msg"]];
            }
        }];
    }
}


- (NSMutableArray *)reviewArray {
    if (!_reviewArray) {
        _reviewArray = [NSMutableArray array];
    }
    return _reviewArray;
}

#pragma mark - 获取用户对职位的收藏信息，并判断本职位是否收藏

- (void)getUserCollected {
    WS(weakSelf)
    [SendRequest getUserCollectedWithType:@"COLLECTION_TYPE_POSITION" result:^(NSDictionary *result, NSError *error) {
        [weakSelf hideProgress:self.view animated:YES];
        result = [CommonUtils decryptDicWithResult:result];
        if([result[@"result"] integerValue] == 1) {
            SaintiLog(@"用户对职位的收藏信息列表 = %@", [[result objectForKey:@"data"] objectForKey:@"list"]);
            
            NSArray *datas = [[result objectForKey:@"data"] objectForKey:@"list"];
            if (datas && datas.count > 0) {
                for (NSDictionary *dict in datas) {
                    NSString *positionId_dict = [[dict objectForKey:@"details"] objectForKey:@"positionId"];
                    if ([positionId_dict integerValue] == [self.positionId integerValue]) {
                        self.collectBtn.selected = YES;
                        break;
                    }
                }
            }
        } else {
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
    }];
}

//    _tagBackView.completion = ^(NSArray *selectTags,NSInteger currentIndex) {
//        NSLog(@"selectTags:%@ currentIndex:%ld",selectTags, (long)currentIndex);
//    };
//    _tagBackView.layout.scrollDirection = UICollectionViewScrollDirectionVertical;
//
//    HXTagAttribute *model = [[HXTagAttribute alloc]init];
//    model.borderWidth  = 0;
//    model.borderColor  = kClearColor;
//    model.cornerRadius  = 8;
//    model.titleSize  = 11;
//    model.textColor  = UIColorFromRGB(0x00BCCC);
//    model.normalBackgroundColor  = UIColorFromRGB(0xE7F4F6);
//    model.selectedBackgroundColor  = UIColorFromRGB(0xE7F4F6);
//    model.tagSpace  = 15;
//
//    _tagBackView.tagAttribute = model;
//
//    [_tagBackView reloadData];
//
//    _tagBackView.tags = @[@"员工旅游",@"五险一金",@"领导好相处",@"五险一金",@"领导好相处",@"五险一金",@"领导好相处",@"五险一金",@"领导好相处",@"五险一金",@"领导好相处",@"五险一金",@"领导好相处",@"五险一金",@"领导好相处",@"五险一金",@"领导好相处",@"五险一金",@"领导好相处"];
//
//    [_tagBackView reloadData];
//    CGFloat height = [HXTagsView getHeightWithTags:self.tagBackView.tags layout:self.tagBackView.layout tagAttribute:self.tagBackView.tagAttribute width:kScreenWidth-30];
//    self.heightOfTags.constant = height;


//    _jobTagBackView.completion = ^(NSArray *selectTags,NSInteger currentIndex) {
//        NSLog(@"selectTags:%@ currentIndex:%ld",selectTags, (long)currentIndex);
//    };
//    _jobTagBackView.layout.scrollDirection = UICollectionViewScrollDirectionVertical;
//    _jobTagBackView.tagAttribute = model;

//    _jobTagBackView.tags = @[@"员工旅游",@"五险一金",@"领导好相处"];
//     [_jobTagBackView reloadData];
//    CGFloat jobTagHeight = [HXTagsView getHeightWithTags:_jobTagBackView.tags layout:_jobTagBackView.layout tagAttribute:_jobTagBackView.tagAttribute width:kScreenWidth-30];
//    self.heightOfJobTags.constant = jobTagHeight;
@end
